package com.morizhang.usersys.api.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.morizhang.usersys.api.ApiResult;
import com.morizhang.usersys.api.IService;
import com.morizhang.usersys.api.bean.ErrorDefinition;
import com.morizhang.usersys.api.bean.ErrorDefinitionHolder;
import com.morizhang.usersys.api.bean.UserSysException;
import com.morizhang.usersys.api.dao.BasicUserInfoDao;
import com.morizhang.usersys.api.service.DeleteUserService;
import com.morizhang.usersys.api.service.ServiceAnnotation;
import com.morizhang.usersys.api.utils.ErrorUtils;
import org.mybatis.spring.MyBatisSystemException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

@ServiceAnnotation(name = "DeleteUser")
public class DeleteUserServiceImpl implements DeleteUserService, IService {

    @Autowired
    protected BasicUserInfoDao basicUserInfoDao;

    protected UserSysException userSysException;

    @Override
    @Transactional
    public void deleteUserByUserID(String userID) throws Exception {
        basicUserInfoDao.deleteUser(userID);
    }

    @Override
    public ApiResult callService(JSONObject requestParams) throws Exception {
        ApiResult result = new ApiResult();
        JSONObject requestParamsData = requestParams.getJSONObject("data");
        try {
            String userID = requestParamsData.getString("userID");
            if (userID == null || userID.length() == 0) {
                ErrorDefinition error = ErrorDefinitionHolder.get("NO_DELETE_USER_ID");
                userSysException = ErrorUtils.convertErrorToException(error);
                throw userSysException;
            }
            deleteUserByUserID(userID);
            result.setSuccess(true);
            return result;
        } catch (UserSysException e) {
            result.setSuccess(false);
            result.setFaultMessage(e.getExceptionMessage());
            result.setException(e);
            return result;
        } catch (MyBatisSystemException e) {
            ErrorDefinition error = ErrorDefinitionHolder.get("DELETE_WRITE_ERROR");
            UserSysException ue = ErrorUtils.convertErrorToException(error);
            result.setSuccess(false);
            result.setFaultMessage(ue.getExceptionMessage());
            result.setException(ue);
            return result;
        }
    }

}
